# 生成图形验证码
import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
import os

dir_path = "graphical_easy/"


def get_random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return r, g, b


def get_random_char():
    random_num = str(random.randint(0, 9))
    random_lower = chr(random.randint(97, 122))
    random_upper = chr(random.randint(65, 90))
    return random.choice([random_num, random_lower, random_upper])


def create_image():
    """创建图形验证码"""
    width = 120
    height = 40
    color = get_random_color()
    size = (width, height)
    image = Image.new(mode="RGB", size=size, color=color)
    # 获取画笔对象
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("SourceHanSerifSC-Regular.otf", 22)

    text_char = ""

    for i in range(4):
        random_char = get_random_char()
        text_char = text_char + random_char
        draw.text((10 + i * 30, 0), random_char, get_random_color(), font=font)

    # 绘制干扰线
    # for index in range(random.randint(3, 6)):
    #     x1 = random.randint(0, width)
    #     x2 = random.randint(0, width)
    #     y1 = random.randint(0, height)
    #     y2 = random.randint(0, height)
    #     draw.line((x1, y1, x2, y2), fill=get_random_color())
    #
    # # 绘制干扰点
    # for index in range(30):
    #     draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
    #     x = random.randint(0, width)
    #     y = random.randint(0, height)
    #     draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())

    with open(dir_path + text_char + ".png", "wb") as f:
        image.save(f, format="png")


if __name__ == "__main__":
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
    for i in range(100):
        create_image()
